﻿using Microsoft.Practices.Unity.Configuration;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Unity;
using Unity.Resolution;

namespace DevFramework.Unity
{
    public class UnityIocHelper 
    {
        //单例
        private static UnityIocHelper instance;

        //ioc容器
        public IUnityContainer container;

        //获取单例
        public static UnityIocHelper getInstance()
        {
            if (instance == null || instance.container == null)
            {
                string configFile = "Unity.config";
                var fileMap = new ExeConfigurationFileMap { ExeConfigFilename = configFile };
                //从config文件中读取配置信息
                Configuration configuration = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);
                //获取指定名称的配置节
                UnityConfigurationSection section = (UnityConfigurationSection)configuration.GetSection("unity");
                instance = new UnityIocHelper()
                {
                    container = new UnityContainer().LoadConfiguration(section, "MyContainer")
                };
            }
            return instance;
        }

        /// <summary>
        /// IOC注入实体
        /// 无参构造函数
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public static T GetInstanceDAL<T>()
        {
            return getInstance().container.Resolve<T>();
        }
        /// <summary>
        /// IOC注入实体
        /// 带参构造函数
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="parameters"></param>
        /// <returns></returns>
        public static T GetInstanceDAL<T>(Dictionary<string,object> parameters)
        {
            var list = new ParameterOverrides();
            foreach (var item in parameters)
            {
                list.Add(item.Key, item.Value);
            }
            return getInstance().container.Resolve<T>(list);
        }
    }
}
